package psbc.daily.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import psbc.daily.entity.User;
import psbc.daily.entity.vo.LoginVo;
import psbc.daily.mapper.UserMapper;
import psbc.daily.properties.JwtProperties;
import psbc.daily.result.Result;
import psbc.daily.util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody User user){
        log.info("登录用户名:{},登录密码:{}",user.getAccount(),user.getPassword());
        User user1 = userMapper.selectUser(user);
        if (user1==null){
            return Result.error("该账户不存在，请注册");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId",user1.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        log.info("token:{}",token);
        LoginVo loginVo = LoginVo.builder()
                .id(user1.getId())
                .token(token)
                .build();

        return Result.success(loginVo);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        log.info("注册用户名:{},注册密码:{}",user.getAccount(),user.getPassword());
        int i = userMapper.insertUser(user);
        if (i>0){
            return Result.success("注册成功");
        }else {
            return Result.error("注册失败");
        }
    }

    @GetMapping("/{id}")
    public String out(@PathVariable int id)
    {
        return "退出成功";
    }
}
